package com.java.permission.common.exception;


import com.java.permission.common.enums.ResultCode;
import com.java.permission.common.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import org.springframework.web.bind.MethodArgumentNotValidException;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理异常业务
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        if (e instanceof MessageException) {
            logger.error("######  业务异常：{}", e.getMessage());
            return Result.error(e.getMessage(), null);
        }

        if (e instanceof AuthException) {
            logger.error("######  权限相关的异常：{}", ((AuthException) e).getResultCode().getMessage());
            return new Result(((AuthException) e).getResultCode().getCode(), ((AuthException) e).getResultCode().getMessage(), null);
        }

        if (e instanceof MissingServletRequestParameterException) {
            return Result.error("缺少必要的参数", null);
        }
        if (e instanceof ParamsException) {
            return new Result(ResultCode.PARAM_ERROR.getCode(), e.getMessage(), null );
        }
        logger.error("######  系统异常：", e);



        return Result.error(null);
    }


    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        return new Result(ResultCode.PARAM_ERROR.getCode(), e.getBindingResult().getFieldError().getDefaultMessage(), null);
    }

    @ExceptionHandler(BindException.class)
    public Result handBindException(BindException e) {
        return new Result(ResultCode.PARAM_ERROR.getCode(), e.getBindingResult().getFieldError().getDefaultMessage(), null);
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(ValidationException e) {
        logger.error(e.getMessage(), e);
        return new Result(ResultCode.PARAM_ERROR.getCode(), e.getCause().getMessage(), null);
    }

    /**
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleConstraintViolationException(ConstraintViolationException e) {
        logger.error(e.getMessage(), e);
        return new Result(ResultCode.PARAM_ERROR.getCode(), e.getMessage(), null);
    }
}
